<?php

namespace frontend\modules\shop\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\shop\ShopProduct;
use common\models\shop\ShopGoods;
use common\models\shop\ShopCart;

/**
 * 购物车结算准备处理模型
 * 
 * @author emhome<emhome@163.com>
 * @since 2.0
 */
class CartPrepareForm extends \common\base\Model {

    /**
     * @var integer 下单用户ID
     */
    public $user_id;

    /**
     * @var array 结算内容单元
     */
    public $items;

    /**
     * @var array 待结算SKU
     */
    private $_carts;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['items'], 'required'],
            [['user_id'], 'integer'],
            [['items'], 'validateItems'],
        ];
    }

    /**
     * 校验提交商品的信息
     * @param string $attribute the attribute currently being validated
     */
    public function validateItems($attribute) {
        if ($this->hasErrors()) {
            return;
        }
        $items = ArrayHelper::map($this->$attribute, 'id', 'num');
        if (empty($items)) {
            $this->addError($attribute, '准备结算的商品已下架或者库存不足，请更新购物车后重新提交');
        } else {
            $this->_carts = $items;
        }
    }

    public function getWaits() {
        $query = ShopCart::findActive('t')
        ->andWhere(['t.id' => array_keys($this->_carts)])
        ->andWhere(['t.user_id' => $this->user_id])
        ->innerJoinWith([
            'product p' => function ($query) {
                $query->active(ShopProduct::STATUS_ACTIVE);
            },
            'goods g' => function ($query) {
                $query->active(ShopGoods::STATUS_ACTIVE);
            },
        ]);
        return $query->all();
    }

    /**
     * 结算准备处理
     * @return boolean
     */
    public function save() {
        if (!$this->validate()) {
            return $this->dumpError('商品准备失败');
        }

        ShopCart::updateAll(['status' => ShopCart::STATUS_DEFAULT], ['user_id' => $this->user_id]);
        $ckv = $this->_carts;
        $data = $this->getWaits();

        $transaction = Yii::$app->db->beginTransaction();
        try {
            foreach ($data as $cart) {
                $num = $ckv[$cart->id];
                Yii::error([
                    $num,
                    $cart->id,
                    $ckv,
                    $cart->stock,
                ]);
                if ($cart->stock < $num) {
                    $num = $cart->stock;
                }
                $cart->num = $num;
                $cart->status = ShopCart::STATUS_PREPARE_ORDER;
                if (!$cart->save()) {
                    throw new Exception($cart->getErrorMsg());
                }
            }
            $transaction->commit();
        } catch (Exception $e) {
            $transaction->rollBack();
            Yii::error($e->getMessage(), __METHOD__);
            return $this->dumpError($e->getMessage(), false);
        }
        return true;
    }

}
